#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb
import hashlib
import sys

class Update:
	version=None
	scripts=[]
	
	def __init__(self):
		pass
	
class Version:
	major=""
	minor=""
	realease=""
	
	def __init__(self, versionText):
		tabs=versionText.split(".")
		self.major=tabs[0]
		self.minor=tabs[1]
		self.realease=tabs[2]
		
	def toString(self):
		return self.major+"."+self.minor+"."+self.realease
		
	def compare(self, other):
		if int(other.major) < int(self.major):
			return 1
		if int(other.major) > int(self.major):
			return -1
			
		if int(other.minor) < int(self.minor):
			return 1
		if int(other.minor) > int(self.minor):
			return -1
			
		if int(other.realease) < int(self.realease):
			return 1
		if int(other.realease) > int(self.realease):
			return -1
			
		return 0
	
class TransformXmlToUpdate:
	__currentNode__=None
	__updateList__=None
	
	def __init__(self):
		self.readXml()
		
	def readXml(self):
		from xml.dom.minidom import parse
		self.doc=parse("updates.xml")
		
	def getRootElement(self):
		if self.__currentNode__==None:
			self.__currentNode__=self.doc.documentElement
		return self.__currentNode__
		
	def getUpdates(self):
		if self.__updateList__!=None:
			return
		self.__updateList__=[]
		for updates in self.getRootElement().getElementsByTagName("update"):
			if updates.nodeType == updates.ELEMENT_NODE:
				u=Update()
				u.version=Version(updates.attributes["version"].nodeValue)
				try:
					for scripts in updates.getElementsByTagName("script"):
						if scripts.nodeType == scripts.ELEMENT_NODE:
							u.scripts.append(scripts.childNodes[0].nodeValue)
				except:
					print 'Y a une erreur'
				self.__updateList__.append(u)
		return self.__updateList__
		
		
if __name__=="__main__":
	try:
		import configDB
	except:
		print "Impossible d'inclure le fichier de configuration, avez vous copier configDB.dist.py en configDB.py ?"
		exit(1)
	file=open("updateDB.log", "a+r")
	hashCodes=file.read().splitlines()
	
	db=MySQLdb.connect(configDB.serverMySQL, configDB.userMySQL, configDB.passWordMySQL, configDB.baseMySQL)
	c=db.cursor()
	c.execute("SET NAMES 'utf8'")
	c.execute("SET CHARACTER SET utf8")
	
	c.execute("SELECT base FROM version")
	rows=c.fetchall()
	
	versionActuelle=Version(rows[0][0])
	
	print "Version actuelle de la base: "+versionActuelle.toString()
	
	x=TransformXmlToUpdate()
	for u in x.getUpdates():
		if versionActuelle.compare(u.version) <= 0:
			print "Traitement de l'update "+u.version.toString()
			for s in u.scripts:
				try:
					hashCode=hashlib.md5(s.encode("utf-8")+u.version.toString().encode("utf-8")).hexdigest()
					#try:
					#	hashCodes.index(hashCode)
					#except:
					#	print "Celui la y est pas "+hashCode
						#file.write(hashCode+"\n")
						#c.execute(s.encode("utf-8"))
					print s.encode("utf-8")+";"
				except:
					print "Erreur sql dans : "+s
			#c.execute("UPDATE version SET base='"+u.version.toString()+"'")
	c.close()
	file.close()